<template>
  <div>
    <button @click="aa">aaa</button>
    <input id="postFile" type="file" name="logo" @change="fileChange">
    <button type="sub" @click="handleUpload">上传</button>
  </div>
</template>

<script setup>
  import { ref } from 'vue';
  import SparkMD5 from 'spark-md5'
  // const SparkMD5 = require('spark-md5')
  const File = ref(null);
  const hashPercentage = ref(0);
  const chunkList = ref([]);
  const hash = ref("");
  const SIZE = 1 * 1024 * 1024
  let requestList = []

  function resetData () {}
  function aa () {
    fetch('http://192.168.8.111:3000/aa', {
      method: "POST",
      body: JSON.stringify({a:1,b:2}),
      headers: {
        "Content-type": "application/json",
      }
    })
  }

  function fileChange(e) {
    // resetData();
    const [file] = e.target.files;
    console.log(file);
    if (!file) {
      File.value = null;
      return;
    }
    File.value = file;
  }
  // 点击按钮上传文件
  async function handleUpload() {
    const file = File.value;
    if (!file) {
      alert("请选择一个文件吧");
      return;
    }
    resetData();

    // 文件分片
    const fileChunkList = createFileChunk(file);
    hash.value = await calculateHash(fileChunkList);

    const a = fileChunkList.map(({ file }, index) => {
      const data = new FormData()
      data.append('chunk',file)
      data.append('size',file.size)
      data.append('chunkHash',`${hash.value} - ${index}`)
      data.append('fileHash',hash.value)
      data.append('index',index)
      // return {
      //   chunk: file,
      //   size: file.size,
      //   chunkHash: `${hash.value} - ${index}`,
      //   fileHash: hash.value,
      //   index
      // };
      return data
    });
    UploadChunks(a);
  }

  // 文件分片
  function createFileChunk(file, size = SIZE) {
    const fileChunkList = [];
    let cur = 0;
    while (cur < file.size) {
      fileChunkList.push({ file: file.slice(cur, cur + size) });
      cur += size;
    }
    return fileChunkList;
  }

  // 计算hash
  function calculateHash(fileChunkList) {
    return new Promise((resolve, reject) => {
      const spark = new SparkMD5.ArrayBuffer();
      const reader = new FileReader();
      const file = File.value;
      const size = file.size;
      let offset = 2 * 1024 * 1024;
      let chunks = [file.slice(0, offset)];

      let cur = offset;
      while (cur < size) {
        // 最后一块全部加进来
        if (cur + offset >= size) {
          chunks.push(file.slice(cur, cur + offset));
        } else {
          // 中间的 前中后去两个字节
          const mid = cur + offset / 2;
          const end = cur + offset;
          chunks.push(file.slice(cur, cur + 2));
          chunks.push(file.slice(mid, mid + 2));
          chunks.push(file.slice(end - 2, end));
        }
        // 前取两个字节
        cur += offset;
      }

      reader.readAsArrayBuffer(new Blob(chunks));
      reader.onload = (e) => {
        spark.append(e.target.result);
        hashPercentage.value = 100;
        resolve(spark.end());
      };
    });
  }

  // 上传文件切片
  async function UploadChunks(chunkList = []) {
    requestList = chunkList.map((item) => {
      console.log(item);
      return uploadChunks(item)
    });
    
    await Promise.all(requestList)
    MergeChunks()
  }

  function uploadChunks(v) {
    return fetch('http://192.168.8.111:3000/chunk', {
      method: "POST",
      body: v,
      // headers: {
      //   "Content-type": "multipart/form-data",
      // }
    })
  }
  function mergeChunks(item) {
    return fetch('http://192.168.8.111:3000/merge', {
      method: "POST",
      body: item,
      headers: {
        "Content-type": "application/json",
      }
    })
  }

  // 通知服务器合并切片
  function MergeChunks() {
    mergeChunks(
      JSON.stringify({
        fileName: File.value.name,
        fileSize: File.value.size,
        size: SIZE,
        hash: hash.value,
      })
    );
  }
  function upload () {
    
  }

  



  // const upload = async () => {
  //       const body = new FormData()
  //       const postFile = document.getElementById('postFile')
  //       if (postFile.files[0]) {
  //           for (const file of postFile.files) {
  //               body.append('logo', file)
  //           }
  //           const response = await fetch('http://localhost:3000/postFile', {
  //               method: 'post',
  //               body
  //           })
  //           const res = await response.json()
  //           console.log(res)
  //       } else {
  //           alert('请选择文件！')
  //       }

  //   }

</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
